// pages/repairrecord/repairrecord.js
const dateutil = require('../../utils/date_util.js')
const httprequest = require('../../utils/http_utils.js')
const common = require('../../utils/common.js')
const app = getApp()
Page({

  /*
   * 页面的初始数据
   */
  data: {
    title: '新增维修记录',
    RepairTime: '', //维修时间
    RepairPerson: '', //维修人
    RepairPersonRowGuid: '', //维修人guid
    resultitems: [{
        name: '未修好',
        value: 0,
        checked: 'true'
      },
      {
        name: '已修好',
        value: 1
      },
    ],
    feeitems: [{
        name: '否',
        value: 0,
        checked: 'true'
      },
      {
        name: '是',
        value: 1
      },
    ],
    is_repair: false, //是否修好
    is_fee: false, //是否收费
    showyulan: true, //是否显示预览
    showsubmit: false, //是否显示提交
    isyulan: false, //是否是预览状态
    error: '',
    success: '',
    remark: '', //内容备注、收费明细
    remark_text: '内容备注',
    signatureTempPath: '', //签名临时路径
    signatureBase64: '', //签名base64
    WorkOrderRowGuid: '',
    IsRepair: '0',
    Expenses: '',
    WorkOrderState: '3',
    FileGuid: [],
    imgs: [],
    picnum: 0, //已上传图片数量
    topHight: 0,
    imgs2: [], //用于过渡图片地址和rowguid关系
    IsCharge: 0, //是否收费
    ArtificialCost: 0, //人工费
    MaterialCost: 0, //材料费
    regular:false, //判断是否使用正则表达式
  },

  resultChange: function(e) {
    console.log(e.detail.value)
    this.setData({
      IsRepair: e.detail.value,
      signatureBase64: '',
      signatureTempPath: ''
    })
    if (e.detail.value == '1') {
      this.setData({
        is_repair: true,
        WorkOrderState: '11',
      })

      if (this.data.IsCharge == 0) {
        this.setData({
          feeitems: [{
              name: '否',
              value: 0,
              checked: 'true'
            },
            {
              name: '是',
              value: 1
            },
          ],
          is_fee: false,
          remark_text: '内容备注'
        })
      } else if (this.data.IsCharge == 1) {
        this.setData({
          feeitems: [{
              name: '否',
              value: 0
            },
            {
              name: '是',
              value: 1,
              checked: 'true'
            },
          ],
          is_fee: true,
          remark_text: '收费明细'
        })
      }
    } else {
      this.setData({
        is_repair: false,
        WorkOrderState: '3',
        feeitems: [{
            name: '否',
            value: 0,
            checked: 'true'
          },
          {
            name: '是',
            value: 1
          },
        ],
        is_fee: false,
        remark_text: '内容备注'
      })
    }
  },

  feeChange: function(e) {
    if (e.detail.value == '1') {
      this.setData({
        is_fee: true,
        remark_text: '收费明细',
        IsCharge: 1
      })
    } else {
      this.setData({
        is_fee: false,
        remark_text: '内容备注',
        IsCharge: 0
      })
    }
    this.setData({
      isCharge: e.detail.value
    })
  },

  //校验维修费用是否为数字
  // checkExp: function(e) {
  //   var expense = e.detail.value
  //   console.log(e.detail.value)
  //   var _this = this
  //   var reg = /^\d+(\.\d+)?$/;
  //   var reg2 = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;
  //   if (expense == "" || expense == null || expense == undefined) {
  //     return
  //   } else {
  //     if (!reg.test(expense)) {
  //       this.setData({
  //         error: '维修费用只能输入数字'
  //       })
  //     } else if (!reg2.test(expense)) {
  //       this.setData({
  //         error: '维修费用最多两位小数'
  //       })
  //     }
  //   }
  // },

  qianming: function() {
    if (this.data.isyulan == false) {
      wx.navigateTo({
        url: '/pages/signature/signature',
      })
    }
  },

  textareaChange: function(e) {
    this.setData({
      remark: e.detail.value
    })
  },

  //人工费
  bindArtificial: function(e) {
    if (e.detail.value == null || e.detail.value == "" || e.detail.value == undefined) {
      this.setData({
        ArtificialCost: 0
      })
    } else {
      this.setData({
        ArtificialCost: e.detail.value
      })
    }

  },

  //材料费
  bindMaterial: function(e) {
    if (e.detail.value == null || e.detail.value == "" || e.detail.value == undefined) {
      this.setData({
        MaterialCost: 0
      })
    } else {
      this.setData({
        MaterialCost: e.detail.value
      })
    }
  },

  //预览
  submit_yulan: function() {
    if (this.data.remark.length == 0) {
      this.setData({
        error: '请填写' + this.data.remark_text
      })
      return false
    }
    if (this.data.signatureTempPath.length == 0 && this.data.is_repair == true) {
      this.setData({
        error: '请签名'
      })
      return false
    } else {
      this.setData({
        showyulan: false,
        showsubmit: true,
        isyulan: true
      })
    }
  },

  //取消
  submit_quxiao: function() {
    this.setData({
      showyulan: true,
      showsubmit: false,
      isyulan: false
    })
  },

  //选择图片
  chooseimage: function() {
    var that = this
    // var fileRowGuid = that.data.FileGuid;
    var newImgs = that.data.imgs;
    var imgs_2 = that.data.imgs2
    wx.chooseImage({
      count: 9 - that.data.imgs.length,
      sizeType: ['compressed'],
      sourceType: ['album', 'camera'],
      success(res) {
        const tempFilePaths = res.tempFilePaths
        console.log("tempFilePaths", tempFilePaths)
  
        for (var i = 0; i < tempFilePaths.length; i++) {
          newImgs.push(tempFilePaths[i])

          let path = tempFilePaths[i]
          
          //压缩图片
          wx.compressImage({
            src: tempFilePaths[i],
            quality: 80,
            success: function(res) {
              console.log('压缩图片', res)
              var tempimgpath = res.tempFilePath
              const uploadFile = wx.uploadFile({
                url: httprequest.host + httprequest.apiInfo.MultipleFileUploadMobileApi,
                filePath: tempimgpath,
                name: dateutil.getNowTime(),
                header: {
                  "Content-Type": "multipart/form-data"
                },
                formData: {
                  FileType: '维修记录'
                },
                success: function(res) {
                  console.log(res)
                  var param = {
                    path: path,
                    path2: tempimgpath,
                    RowGuid: JSON.parse(res.data).RowGuid,
                    FileGuid: JSON.parse(res.data).FileGuid
                  }
                  imgs_2.push(param)
                },
                fail: function(err) {
                  that.setData({
                    error: '图片上传失败'
                  })
                  console.error(err)
                }
              })
              uploadFile.onProgressUpdate((res) => {
                console.log("上传进度", res.progress)
                if (res.progress == 100) {
                  wx.hideLoading()
                } else {
                  wx.showLoading({
                    title: '图片已上传' + res.progress + '%',
                  })
                }
              })
            },
            fail: function(err) {
              console.error(('压缩图片失败', err))
            }
          })
        }
        that.setData({
          imgs2: imgs_2,
          imgs: newImgs,
          picnum: that.data.imgs.length,
        })
        console.log('-----imgs---', that.data.imgs)
        console.log('-----imgs2---', that.data.imgs2)
      }
    })
  },

  //删除图片
  deleteImg: function(e) {
    var that = this;
    wx.showModal({
      title: '删除图片',
      content: '确定删除图片',
      confirmText: '删除',
      success: function(res) {
        if (res.confirm) {
          let index = e.currentTarget.dataset.index;
          let imgs = that.data.imgs;
          let imgs_2 = that.data.imgs2;
          // console.log('删除前的imgs_2', imgs_2)
          let filepath = e.currentTarget.dataset.filepath
          if (that.data.isyulan == false) {
            // that.data.FileGuid.splice(index, 1)
            for (var i = 0; i < imgs_2.length; i++) {
              if (imgs_2[i].path == filepath) {
                var param = {
                  RowGuid: imgs_2[i].RowGuid
                }
                // console.log('删除的RowGuid----', imgs_2[i].RowGuid)
                httprequest.GetValidateRequest(httprequest.apiInfo.MultipleFileDeleteMobileApi, param,
                  function(res) {
                    console.log('删除的结果---', res)
                  },
                  function(err) {
                    console.error(err)
                  })
                imgs_2.splice(i, 1)
              }
            }
            imgs.splice(index, 1)
            that.setData({
              imgs2: imgs_2,
              imgs: imgs,
              picnum: that.data.imgs.length
            })
          }
        }
      }
    })
  },

  //提交
  submit: function() {
    var that = this
    var reg = /^\d+(\.\d+)?$/;
    var reg2 = /^(?!0+(?:\.0+)?$)(?:[1-9]\d*|0)(?:\.\d{1,2})?$/;

    if (that.data.IsRepair == 0 || that.data.IsCharge == 0){
      console.log("跳过正则")
    }else{
      if (!reg.test(that.data.ArtificialCost) || !reg.test(that.data.MaterialCost)) {
        this.setData({
          error: '维修费用只能输入数字'
        })
        return
      }else if (that.data.ArtificialCost == 0 && that.data.MaterialCost == 0){

      }else if (that.data.ArtificialCost == 0){
        if (!reg2.test(that.data.MaterialCost)) {
          this.setData({
            error: '维修费最多两位小数'
          })
          return
        }
      } else if (that.data.MaterialCost == 0){
        if (!reg2.test(that.data.ArtificialCost)) {
          this.setData({
            error: '维修费最多两位小数'
          })
          return
        }
      }else{
        if (!reg2.test(that.data.ArtificialCost) || !reg2.test(that.data.MaterialCost)) {
          this.setData({
            error: '维修费最多两位小数'
          })
          return
        }
      }
      
    }

    var TotalPrice = parseFloat(that.data.ArtificialCost) + parseFloat(that.data.MaterialCost);

    if (TotalPrice == 0) {
      that.setData({
        Expenses: '免费'
      })
    } else {
      that.setData({
        Expenses: String(TotalPrice)
      })
    }
    console.log('remark', that.data.remark.length)
    if (that.data.remark.length == 0) {
      that.setData({
        error: '请填写' + that.data.remark_text
      })
      return false
    }
    if (this.data.signatureTempPath.length == 0 && this.data.is_repair == true) {
      that.setData({
        error: '请签名'
      })
      return false
    } else {
      var imgs2 = that.data.imgs2
      var temp = that.data.FileGuid
      if (imgs2.length > 0) {
        for (var i = 0; i < imgs2.length; i++) {
          var param1 = {
            RowGuid: imgs2[i].RowGuid,
            FileGuid: imgs2[i].FileGuid
          }
          temp.push(param1)
        }
        that.setData({
          FileGuid: temp
        })
        console.log('FileGuid------', that.data.FileGuid)
      }
      var param = {
        WorkOrderRowGuid: that.data.WorkOrderRowGuid,
        RepairPersonRowGuid: that.data.RepairPersonRowGuid,
        IsRepair: that.data.IsRepair,
        RepairTime: that.data.RepairTime,
        Remark: that.data.remark,
        Expenses: that.data.Expenses,
        LaborFees: that.data.ArtificialCost, //人工费
        MaterialFees: that.data.MaterialCost, //材料费
        PicUrl: that.data.signatureBase64,
        WorkOrderState: that.data.WorkOrderState,
        FileGuid: that.data.FileGuid,
        IsCharge: that.data.IsCharge
      };
      console.log(JSON.stringify(param))
      httprequest.PostValidateRequest(httprequest.apiInfo.AddWxjlApi, param,
        function(res) {
          console.log(res)
          if (res == '0') {
            that.setData({
              success: '新增维修记录成功'
            })
            if (that.data.WorkOrderState == '3') {
              wx.redirectTo({
                url: '/pages/success/success?type=record&state=3&WorkOrderRowGuid=' + that.data.WorkOrderRowGuid,
              })
            } else {
              wx.redirectTo({
                url: '/pages/success/success?type=record&state=11&WorkOrderRowGuid=' + that.data.WorkOrderRowGuid,
              })
            }
          } else {
            that.setData({
              error: '新增维修记录失败'
            })
          }
        },
        function(err) {
          console.error(err)
          that.setData({
            error: '新增维修记录失败'
          })
        })
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    console.log(options)
    if (options.WorkOrderGuid != undefined && options.WorkOrderGuid != '') {
      this.setData({
        WorkOrderRowGuid: options.WorkOrderGuid
      })
    }
    var statusBarHeight = app.globalData.statusBarHeight;
    var titleBarHeight = app.globalData.titleBarHeight;
    this.setData({
      RepairTime: dateutil.getNowDate(),
      RepairPerson: wx.getStorageSync('UserInfo').AppLogin.DisplayName,
      RepairPersonRowGuid: wx.getStorageSync('UserInfo').AppLogin.RowGuid,
      // topHight: statusBarHeight + titleBarHeight
      topHight: ((app.globalData.titleBarHeight + app.globalData.statusBarHeight) * 2) + 110
    })

    console.log(options.IsCharge + "-------------是否收费")
    this.setData({
      IsCharge: options.IsCharge
    })

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {

  }
})